﻿using System;
using Best.SmartCms.Dto.Common;
using Best.SmartCms.Portal.Models;
using Best.SmartCms.Service.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace Best.SmartCms.Portal.Extensions
{
    public class ViewBagFilter : IActionFilter
    {
        private readonly IMemoryCache _cache;
        private readonly SiteSettingService _settingService;
        public ViewBagFilter(IMemoryCache memoryCache, SiteSettingService settingService)
        {
            _cache = memoryCache;
            _settingService = settingService;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!(context.Controller is Controller controller)) return;
            var baseModel = _cache.Get<SiteSettingDto>("BaseViewBagModel");
            if (baseModel == null)
            {
                baseModel = _settingService.Info();
                _cache.Set("BaseViewBagModel", baseModel, TimeSpan.FromHours(24));
            }

            if (baseModel == null) return;
            controller.ViewBag.Title = baseModel.SiteName + " - " + baseModel.Title;
            controller.ViewBag.MetaDescription = baseModel.Meta;
            controller.ViewBag.MetaKeywords = baseModel.MetaKeywords;
            controller.ViewBag.DomainUrl = baseModel.DomainUrl;
            controller.ViewBag.DomainCaseNumber = baseModel.DomainCaseNumber;
            controller.ViewBag.CompanyName = baseModel.CompanyName;
            controller.ViewBag.CompanyAdress = baseModel.CompanyAdress;
            controller.ViewBag.CompanyPhone = baseModel.CompanyPhone;
            controller.ViewBag.SiteName = baseModel.SiteName;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }
    }

}